"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : a-partition-autoextend
Case Name   : partition auto extend-- copy to copy from
Create At   : 2021/10/18
Owner       : @wan005
Description :
    1.修改配置文件将日志归档模式打开
    2.重启数据库使参数设置生效
    3.查看归档日志模式
    4.配置归档路径和参数,执行select pg_switch_xlog();触发归档
    5.查看是否生成归档日志
    6.删除归档目录
    7.恢复默认值
Expect      :
    1.配置文件中archive_mode设置完成
    2.重启数据库成功
    3.查看归档日志模式
    4.配置归档路径及参数archive_command成功
    5.WAL日志正常归档
    6.删除归档日志
    7.恢复默认值
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import macro
from yat.test import Node

COMMONSH = CommonSH("PrimaryDbUser")


class TestUstore(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(
            "Opengauss_Function_Ustore_Partition_Autoextend_Case0045 start")
        self.pri_sh = CommonSH("PrimaryDbUser")
        self.constant = Constant()
        self.com = Common()
        self.user_node = Node("PrimaryDbUser")
        result = self.pri_sh.get_db_cluster_status("detail")
        self.log.info(result)
        self.assertTrue("Degraded" in result or "Normal" in result,
                        "数据库状态异常，未执行")
        self.file_path = os.path.join(
            os.path.dirname(macro.DB_INSTANCE_PATH), "us_pextend_0045.dat")
        self.t_name1 = "t_ustore_0045_01"
        self.t_name2 = "t_ustore_0045_02"

    def test_main(self):
        text = "--step1:建表，插入数据;expect:成功"
        self.log.info(text)
        sql = f'''drop table if exists  cascade;
                drop table if exists {self.t_name2} cascade;
                create table {self.t_name1}(
                col_1 smallint,
                col_2 char(30),
                col_3 int,
                col_4 date,
                col_5 boolean,
                col_6 nchar(30),
                col_7 float
                ) with (storage_type=ustore)
                partition by range (col_4)
                interval ('1 month')
                (
                partition {self.t_name1}_p1 values less than ('2020-03-01'),
                partition {self.t_name1}_p2 values less than ('2020-04-01'),
                partition {self.t_name1}_p3 values less than ('2020-05-01')
                );
                
                create table {self.t_name2}(
                col_1 smallint,
                col_2 char(30),
                col_3 int,
                col_4 date,
                col_5 boolean,
                col_6 nchar(30),
                col_7 float
                ) with (storage_type=ustore)
                partition by range (col_4)
                interval ('1 month')
                (
                partition {self.t_name2}_p1 values less than ('2020-04-01'),
                partition {self.t_name2}_p2 values less than ('2020-05-01'),
                partition {self.t_name2}_p3 values less than ('2020-06-01')
                );
                
                insert into {self.t_name1} values 
                (1,'aaa',1,'2020-02-23',true,'aaa',1.1);
                insert into {self.t_name1} values 
                (2,'bbb',2,'2020-03-23',false,'bbb',2.2);
                insert into {self.t_name1} values 
                (3,'ccc',3,'2020-04-23',true,'ccc',3.3);
                insert into {self.t_name1} values 
                (4,'ddd',4,'2020-05-23',false,'ddd',4.4);
                insert into {self.t_name1} values 
                (5,'eee',5,'2020-06-23',true,'eee',5.5);
                insert into {self.t_name1} values 
                (6,'fff',6,'2020-07-23',false,'fff',6.6);
                '''
        result = self.pri_sh.execut_db_sql(sql)
        self.log.info(result)
        self.assertNotIn("ERROR", result, "执行失败:" + text)
        self.assertEqual(result.count(self.constant.TABLE_CREATE_SUCCESS), 2,
                         "执行失败:" + text)
        self.assertEqual(result.count(self.constant.INSERT_SUCCESS_MSG), 6,
                         "执行失败:" + text)

        text = "--step2:copy to copy from;expect:成功"
        self.log.info(text)
        sql = f"copy {self.t_name1} to '{self.file_path}';" \
              f"copy {self.t_name2} from '{self.file_path}';"
        result = self.pri_sh.execut_db_sql(sql)
        self.log.info(result)
        self.assertNotIn("ERROR", result, "执行失败:" + text)
        self.assertEqual(result.count("COPY 6"), 2, "执行失败:" + text)

        text = "核对copy from结果"
        self.log.info(text)
        sql = f"select relname, parttype, partstrategy, boundaries " \
              f"from pg_partition where parentid = " \
              f"(select oid from pg_class " \
              f"where relname = '{self.t_name2}') order by relname;"
        result = self.pri_sh.execut_db_sql(sql)
        self.log.info(result)
        self.assertNotIn("ERROR", result, "执行失败:" + text)
        self.assertIn("6 rows", result, "执行失败:" + text)

    def tearDown(self):
        text = "--step3:清理环境;expect:成功"
        self.log.info(text)
        shell_result = self.com.get_sh_result(self.user_node,
                                              f"rm -rf {self.file_path}")
        self.log.info(shell_result)
        sql = f"drop table if exists {self.t_name1} cascade;" \
              f"drop table if exists {self.t_name2} cascade;"
        result = self.pri_sh.execut_db_sql(sql)
        self.log.info(result)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, result, "执行失败:" + text)
        self.assertNotIn("bash", shell_result, "执行失败:" + text)
        self.assertEqual("", shell_result, "执行失败:" + text)
        self.log.info(
            "Opengauss_Function_Ustore_Partition_Autoextend_Case0045 finsh")
